package cool.tianyou.blue.bird.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.google.common.collect.ImmutableMap;

import cool.tianyou.blue.bird.constant.Constant;
import cool.tianyou.blue.bird.dialog.LoadingDialog;
import cool.tianyou.blue.bird.model.ApiResult;
import cool.tianyou.blue.bird.model.Device;
import cool.tianyou.blue.bird.util.HttpUtil;

import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

import cool.tianyou.blue.bird.R;


public class DeviceListAdapter extends BaseAdapter {
    private static final int DEVICE_DELETE = 3;

    private final List<Device> devices;
    /**
     * 设备禁用消息
     */
    private static final int DEVICE_DISABLED = 2;

    /**
     * 设备下线消息
     */
    private static final int DEVICE_OFFLINE = 1;

    private AlertDialog dialog;

    private LoadingDialog loadingDialog;

    private final LayoutInflater mLayoutInflate;
    private final Context context;
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case DEVICE_DISABLED: {
                    Device device = (Device) msg.obj;
                    String status = "启用";
                    if (device.getDisabled()) {
                        status = "禁用";
                    }
                    Toast.makeText(context, "设备" + status + "成功", Toast.LENGTH_LONG).show();
//                    LogUtil.recordLog(true, new Log(MessageTypeEnum.DEVICE, Collections.singletonList(device.getAlias()), "设备" + status + "成功",null));
                    MainActivity.instance.getBatteryImmediately();
                    break;
                }
                case DEVICE_OFFLINE: {
//                    Device device = (Device) msg.obj;
//                    LogUtil.recordLog(true, new Log(MessageTypeEnum.DEVICE, Collections.singletonList(device.getAlias()), "设备下线成功",null));

                }

            }
            //重新加载数据
            DeviceActivity activity = (DeviceActivity) DeviceListAdapter.this.context;
            activity.init();
            notifyDataSetChanged();
        }
    };

    public DeviceListAdapter(List<Device> devices, Context context) {
        this.devices = devices;
        mLayoutInflate = LayoutInflater.from(context);
        this.context = context;
    }

    @Override
    public int getCount() {
        return devices.size();
    }

    @Override
    public Object getItem(int position) {
        return devices.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("ViewHolder")
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (position >= devices.size()) {
            return convertView;
        }
        Device device = devices.get(position);
        convertView = mLayoutInflate.inflate(R.layout.device_list_item, parent, false);
        TextView tvName = convertView.findViewById(R.id.tv_name);
        TextView tvCurrent = convertView.findViewById(R.id.device_tv_current);
        tvName.setText(device.getAlias());
        ImageView imageView = convertView.findViewById(R.id.iv_device_icon);
        int icon;
        switch (device.getType()) {
            case "mobile":
                icon = R.mipmap.phone;
                break;
            case "Darwin":
                icon = R.mipmap.mac;
                break;
            default:
                icon = R.mipmap.windows;
        }
        imageView.setImageResource(icon);
        Button btnOffline = convertView.findViewById(R.id.btn_offline);
        Button btnDelete = convertView.findViewById(R.id.btn_del);
        btnOffline.setVisibility(device.isOnLine() ? android.view.View.VISIBLE : android.view.View.INVISIBLE);
        ImageView lockStatus = convertView.findViewById(R.id.iv_lock_status);
        lockStatus.setImageResource(device.getDisabled() ? R.mipmap.lock : R.mipmap.unlock);
        lockStatus.setOnClickListener((buttonView) -> {
            toggleStatus(device, position, !device.getDisabled());
        });
        if (Objects.equals(device.getDeviceName(), Constant.USER_INFO.DEVICE_INFO)) {
            btnDelete.setVisibility(View.INVISIBLE);
            btnOffline.setVisibility(View.INVISIBLE);
            lockStatus.setVisibility(View.INVISIBLE);
            tvName.setText(device.getAlias());

        } else {
            tvCurrent.setVisibility(View.INVISIBLE);
        }
        convertView.setOnClickListener((v) -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // 加载布局文件
            View mLayout = inflater.inflate(R.layout.dialog_layout, null, false);
            // 添加布局文件到 Dialog
            builder.setView(mLayout);

            EditText etAlias = mLayout.findViewById(R.id.et_dialog_alias);
            Button button = mLayout.findViewById(R.id.btn_dialog_ok);
            etAlias.setHint(device.getAlias());
            button.setOnClickListener(v1 -> {
                String s = etAlias.getText().toString();
                if (s == null || s.trim().length() == 0) {
                    s = etAlias.getHint().toString();
                }
                System.out.println(s);
                changeAlias(device.getId(), s, position);
            });
            dialog = builder.show();
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            dialog.show();//要放在最前面
            Window dialogWindow = dialog.getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL);
            lp.width = 800; // 宽度
            dialogWindow.setAttributes(lp);

        });
        btnOffline.setOnClickListener(v -> offline(device, position));
        btnDelete.setOnClickListener(v -> delete(device.getId(), position));
        return convertView;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void offline(Device device, Integer pos) {
        loadingDialog = new LoadingDialog(this.context, "正在下线...").showDialog();
        HttpUtil.post(context, null, "/device/offline/" + device.getId(), new Consumer<ApiResult<?>>() {
            @Override
            public void accept(ApiResult<?> apiResult) {
                devices.get(pos).setOnLine(false);
                handler.sendMessage(handler.obtainMessage(DEVICE_OFFLINE, device));
                loadingDialog.dismiss();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void changeAlias(Integer deviceId, String newName, Integer pos) {
        ImmutableMap<Object, Object> build = ImmutableMap.builder().put("deviceId", deviceId).put("alias", newName).build();
        HttpUtil.put(context, build, "/device/alias", apiResult -> {
            devices.get(pos).setAlias(newName);
            handler.sendEmptyMessage(DEVICE_DELETE);
            dialog.dismiss();
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void delete(Integer deviceId, Integer pos) {
        loadingDialog = new LoadingDialog(this.context, "正在删除设备...").showDialog();
        HttpUtil.delete(context, null, "/device/" + deviceId, apiResult -> {
            devices.get(pos).setOnLine(false);
            handler.sendEmptyMessage(DEVICE_DELETE);
            loadingDialog.dismiss();
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void toggleStatus(Device device, Integer pos, boolean check) {
        loadingDialog = new LoadingDialog(this.context, "正在切换锁定状态...").showDialog();
        ImmutableMap<Object, Object> param = ImmutableMap.builder().put("lock", check)
                .put("deviceId", device.getId())
                .build();
        HttpUtil.put(context, param, "/device/status", apiResult -> {
            Message message = handler.obtainMessage();
            message.what = DEVICE_DISABLED;
            device.setDisabled(check);
            message.obj = device;
            devices.get(pos).setDisabled(check);
            handler.sendMessage(message);
            loadingDialog.dismiss();
        });
    }


}
